package com.casework

import javax.servlet.FilterChain
import javax.servlet.ServletRequest
import javax.servlet.ServletResponse
import javax.servlet.http.HttpServletResponse
import javax.servlet.http.HttpServletResponseWrapper
import javax.servlet.ServletOutputStream
import javax.servlet.http.HttpServletRequest

class SearchResponseFilter extends org.springframework.web.filter.GenericFilterBean {

    void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) {
        ServletResponse wrappedResponse = response

        if (request instanceof HttpServletRequest) {
            wrappedResponse = new CharResponseWrapper((HttpServletResponse) response)
        }

        def freeTextSearch = request.getParameter("textQuery")

        chain.doFilter(request, wrappedResponse)

        if (wrappedResponse instanceof CharResponseWrapper) {
            String text = wrappedResponse.toString()
            if (text != null && freeTextSearch) {
                freeTextSearch.split(' ').each{
                    text = text.replaceAll(it, "<strong>$it</strong>")
                }
                response.getWriter().write(text)
            }
        }

    }
}


class CharResponseWrapper extends HttpServletResponseWrapper {
    protected CharArrayWriter charWriter

    protected PrintWriter writer

    protected boolean getOutputStreamCalled

    protected boolean getWriterCalled

    public CharResponseWrapper(HttpServletResponse response) {
        super(response)

        charWriter = new CharArrayWriter()
    }

    public ServletOutputStream getOutputStream() throws IOException {
        if (getWriterCalled) {
            throw new IllegalStateException("getWriter already called")
        }

        getOutputStreamCalled = true
        return super.getOutputStream()
    }

    public PrintWriter getWriter() throws IOException {
        if (writer != null) {
            return writer
        }
        if (getOutputStreamCalled) {
            throw new IllegalStateException("getOutputStream already called")
        }
        getWriterCalled = true
        writer = new PrintWriter(charWriter)
        return writer
    }

    public String toString() {
        String s = null

        if (writer != null) {
            s = charWriter.toString()
        }
        return s
    }
}